package com.xzy.order_service.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.xzy.order_service.service.OrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("api/v1/order/")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("save")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object save(@RequestParam("user_id") int userId, @RequestParam("product_id") int productId, HttpServletRequest request){
            Map<String,Object> res=new HashMap<>();
        res.put("code",0);
        res.put("data",orderService.save(userId,productId));
        return res;
    }
    private Object saveOrderFail(int userId,int productId, HttpServletRequest request){
        Map<String,Object> res=new HashMap<>();
        res.put("code",-1);
        res.put("msg","网站太火爆，您被挤下来了。。。");

        new Thread(()->{
            String orderKey="order-service";
            String msg=redisTemplate.opsForValue().get(orderKey);
            String ip=request.getRemoteHost();
            if(StringUtils.isBlank(msg)){
                System.out.println("发送短信");
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                redisTemplate.opsForValue().set(orderKey,sdf.format(new Date())+"出问题啦，赶紧处理，服务器ip:"+ip,20, TimeUnit.SECONDS);
            }else{
                System.out.println("短信已经发送："+msg);
            }
        }).start();
        return res;
    }
}
